/*
 * @Author: ZhaoZhiqi
 * @Date: 2024-09-03 16:53:42
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2024-10-16 17:22:58
 * @Description: http
 * @FilePath: \charging-mini\充电项目\src\api\http.js
 */

import axios from "axios";
import mpAdapter from "axios-miniprogram-adapter";
import { baseUrl } from "./baseUrl";

axios.defaults.adapter = mpAdapter;
function handleResponse(res) {
    if (res.status === 200) {
        return res.data;
    } else {
        uni.showToast({
            title: "网络错误",
            icon: "none",
        });
        return false;
    }
}

function handleResponseData(res, noToast) {
    console.log("接口返回参数", res);
    if (res.status === 200) {
        return res.data;
    } else if (res.status === 2000) {
        uni.showToast({
            title: "用户未登录或登录超时",
            icon: "none",
        });
        setTimeout(() => {
            uni.removeStorageSync("userInfo");
            uni.removeStorageSync("token");
            uni.reLaunch({
                url: "/pages/index",
            });
        }, 1500);
        return Promise.reject(res);
    } else {
        return Promise.reject(res);
    }
}

function handleError(err) {
    let msg = "";
    if (typeof err === "string") {
        msg = err;
    } else if (err) {
        msg = err.message || err.desc || err;
    } else {
        msg = "未知错误";
    }
    console.log("handleError", msg);
    uni.showToast({
        title: msg.toString() === "Error: Network Error" ? "接口异常，请稍后再试" : msg.toString(),
        icon: "none",
    });
    return Promise.reject(msg.toString(), err);
}

/**
 * @description: 接口调用方法
 * @param {*} options 基础参数
 * @param {*} handleRequestFn 自定义成功回调
 * @param {*} handleErrorFn 自定义失败回调
 * @param {*} basePath 自定义接口路径
 * @return {*}
 */
const http = async (options) => {
    options.handleRequestFn = options && options.handleRequestFn ? options.handleRequestFn : handleResponseData;
    options.handleErrorFn = options && options.handleErrorFn ? options.handleErrorFn : handleError;
    let opt = {
        url: `${baseUrl()}${options.url}`,
        method: options.method || "GET",
        headers: {
            Authorization: uni.getStorageSync("token"),
        },
        params: {
            ...options.params,
        },
        data: {
            ...options.data,
        },
        timeout: 30000,
    };
    console.log("请求参数", opt);
    return axios(opt).then(handleResponse).then(options.handleRequestFn).catch(options.handleErrorFn);
};

export default http;
